package com.jvm.getthreadresult;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

// CountDownLatch 实现
public class Demo2 {

    // 用于封装结果
    static class Result<T> {
        T result;

        public T getResult() {
            return result;
        }

        public void setResult(T result) {
            this.result = result;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(System.currentTimeMillis());
        CountDownLatch countDownLatch = new CountDownLatch(1);
        // 用于存放子线程执行的结果
        Demo1.Result<Integer> result = new Demo1.Result<>();
        // 创建一个子线程
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                result.setResult(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 将 countDownLatch中的计数器 -1
                countDownLatch.countDown();
            }
        });
        thread.start();
        // countDownLatch.await() 会让当前线程阻塞，当 countDownLatch中的计数器变为0的时候，await方法会返回
        countDownLatch.await();

        // 获取thread线程的执行结果
        Integer rs = result.getResult();
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis() + ":" + rs);

        /**
         *
         * 使用CountDownLatch可以让一个或者多个线程等待一批线程完成之后，自己再继续
         *
         */
    }

}
